package com.hx.thread.semaphore;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author Minghua Chen
 * @date 2020-09-05 21:19
 */
public class SemaphoreDemo2 {
    private static final Logger logger = LoggerFactory.getLogger(SemaphoreDemo2.class);
    // 3个信号量
    static Semaphore semaphore = new Semaphore(3);

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 100; i++) {
            service.submit(new Task());
        }
        service.shutdown();
    }

    static class Task implements Runnable {
        @Override
        public void run() {
            try {
                // 获取信号量
                semaphore.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info(Thread.currentThread().getName() + "拿到信号量");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info("慢服务执行完毕," + Thread.currentThread().getName() + "释放信号量");
            // 释放信号量
            semaphore.release();
        }
    }


}
